package com.example.yuejian.yuejian.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.yuejian.yuejian.R;
import com.example.yuejian.yuejian.base.BaseActivity;
import com.example.yuejian.yuejian.bean.UploadImage;
import com.example.yuejian.yuejian.dialog.UploadBackDialog;
import com.example.yuejian.yuejian.model.Contants;
import com.example.yuejian.yuejian.service.ImageUploadService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UploadPhotoActivity extends BaseActivity {
    private ImageView btn_back;

    private static final int PHOTO_REQUEST_CAREMA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final int PHOTO_REQUEST_CUT = 3;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private Context context;
    private EditText Content;
    private File file;
    private ImageView Send;
    private Button tijiao;
    private File tempFile;
    private Retrofit retrofit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_photo);
        back();
        initViews();
        initEvents();

    }

    private void back() {
        btn_back = (ImageView) findViewById(R.id.imgBtn_upload_photo_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UploadBackDialog dialog = new UploadBackDialog();
                dialog.showCallPhoneDialog(UploadPhotoActivity.this);
            }
        });
    }

    private void initViews() {
        Content = (EditText) findViewById(R.id.id_upload_content);
        Send = (ImageView) findViewById(R.id.upload_image);
        tijiao = (Button) findViewById(R.id.btn_commite_image);
    }

    private void initEvents() {
        Send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select();

            }
        });
        tijiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add();
            }
        });

    }

    private void select() {
        final int[] yourChoice = new int[1];

        final String[] items = {"拍照", "本地图片"};
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(UploadPhotoActivity.this);
        singleChoiceDialog.setTitle("选取照片方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice[0] = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice[0] != -1) {
                            if (items[yourChoice[0]].equals("拍照")) {
                                getImageFromCamera();


                            }
                            if (items[yourChoice[0]].equals("本地图片")) {
                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image/*");
                                startActivityForResult(intent,
                                        PHOTO_REQUEST_GALLERY);
                             /* Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image*//*");//相片类型
                                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);*/
                                Toast.makeText(UploadPhotoActivity.this,
                                        "你选择了" + items[yourChoice[0]],
                                        Toast.LENGTH_SHORT).show();

                            }

                        }
                    }
                });
        singleChoiceDialog.show();
    }

    protected void getImageFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);

            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
        } else {
            Toast.makeText(UploadPhotoActivity.this, "未找到存储卡，无法存储照片！",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {

                Uri uri = data.getData();
                Log.e("图片路径？？", data.getData() + "");
                tempFile= uri2File(uri);
               Send.setImageURI(uri);
               // file = new File(uri.toString());
            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
               // file=tempFile;
              //crop(Uri.fromFile(tempFile));
                Send.setImageURI(Uri.fromFile(tempFile));
                //file =new File(tempFile);
            } else {
                Toast.makeText(UploadPhotoActivity.this, "未找到存储卡，无法存储照片！",
                        Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (data != null) {
                final Bitmap bitmap = data.getParcelableExtra("data");
                Send.setImageBitmap(bitmap);
                // 保存图片到internal storage
                FileOutputStream outputStream;
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    // out.close();
                    // final byte[] buffer = out.toByteArray();
                    // outputStream.write(buffer);
                    outputStream = UploadPhotoActivity.this.openFileOutput("_head_icon.jpg", Context.MODE_PRIVATE);
                    out.writeTo(outputStream);
                    out.close();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                if (tempFile != null && tempFile.exists())
                    tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void add() {


        // 创建 RequestBody，用于封装构建RequestBody
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), tempFile);

// MultipartBody.Part  和后端约定好Key，这里的partName是用image
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("photo", tempFile.getName(), requestFile);

// 添加描述
        String descriptionString = "hello, 这是文件描述";
        RequestBody title =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), Content.getText().toString());
        RequestBody userid =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), getUser_id());
        RequestBody clubid =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), getUserclub_id());

        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Contants.BASE_URL1)
                .build();

        ImageUploadService service = retrofit.create(ImageUploadService.class);

// 执行请求
        Call<UploadImage> call = service.uploadPhoto(title, userid, clubid, body);
        call.enqueue(new Callback<UploadImage>() {
            @Override
            public void onResponse(Call<UploadImage> call,
                                   Response<UploadImage> response) {
                UploadImage res=response.body();
              Toast.makeText(getApplication(), res.getRetMsg(),Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(Call<UploadImage> call, Throwable t) {
                Toast.makeText(getApplication(),t.toString(),Toast.LENGTH_SHORT).show();
            }
        });
    }




    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }



}
